package com.jiali.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiali.backend.Utils.UserServiceUtils;
import com.jiali.backend.common.ResponseResult;
import com.jiali.backend.controller.request.AppointmentRequest;
import com.jiali.backend.controller.request.OrderUpdateRequest;
import com.jiali.backend.mapper.AppointmentOrderMapper;
import com.jiali.backend.model.*;
import com.jiali.backend.service.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author piko
 * @description 针对表【appointment_order(预约订单)】的数据库操作Service实现
 * @createDate 2025-03-20 19:20:42
 */
@Service
public class AppointmentOrderServiceImpl extends ServiceImpl<AppointmentOrderMapper, AppointmentOrder>
        implements AppointmentOrderService {
    @Resource
    private VehicleService vehicleService;
    @Resource
    private ServiceItemService serviceItemService;
    @Resource
    private UserServiceUtils userServiceUtils;
    @Resource
    private UserService userService;
    @Resource
    private StaffService staffService;

    @Transactional
    @Override
    public ResponseResult<AppointmentOrder> createAppointment(AppointmentRequest request, HttpServletRequest httpRequest) {
        if (userServiceUtils.IsAdmin(httpRequest) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        User currentUser = userServiceUtils.getCurrentUser(httpRequest);
        // 1. 检查车辆是否已存在
        Vehicle existingVehicle = vehicleService.lambdaQuery()
                .eq(Vehicle::getLicensePlate, request.getLicensePlate())
                .eq(Vehicle::getModel, request.getModel())
                .eq(Vehicle::getUserId, currentUser.getId())
                .one();

        Vehicle vehicle;
        if (existingVehicle != null) {
            // 使用已有车辆
            vehicle = existingVehicle;
        } else {
            // 创建新车辆
            vehicle = new Vehicle();
            vehicle.setUserId(currentUser.getId());
            vehicle.setModel(request.getModel());
            vehicle.setLicensePlate(request.getLicensePlate());
            vehicleService.save(vehicle);
        }

        // 2. 获取服务项ID
        ServiceItem serviceItem = serviceItemService.lambdaQuery()
                .eq(ServiceItem::getServiceName, request.getServiceName())
                .one();
        if (serviceItem == null) {
            throw new RuntimeException("服务项不存在: " + request.getServiceName()); // 增加具体服务名称
        }
        // 转换时间类型
        Date appointmentDate = Date.from(
                request.getAppointmentTime().atZone(ZoneId.systemDefault()).toInstant()
        );
        // 3. 构建预约订单
        AppointmentOrder order = new AppointmentOrder();
        order.setUserId(currentUser.getId());
        order.setVehicleId(vehicle.getId());
        order.setServiceId(serviceItem.getId());
        order.setServiceTechnician(request.getServiceTechnician());
        order.setAppointmentTime(appointmentDate);  // 使用转换后的Date对象
        order.setProblemDescription(request.getProblemDescription());
        order.setStatus(0);

        this.save(order);
        order.setOrderNumber(12000 + order.getId()); // 数值相加
        this.updateById(order); // 更新订单记录
        return ResponseResult.success(order);
    }

    //查询所有订单
    @Override
    public ResponseResult<List<AppointmentOrder>> getAllAppointments(HttpServletRequest httpRequest) {

        if (userServiceUtils.IsAdmin(httpRequest) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(httpRequest)) {
            return ResponseResult.fail(403, "无权限查看所有订单", null);
        }

        List<AppointmentOrder> orders = this.list();
        enrichOrderDetails(orders);
        return ResponseResult.success(orders);
    }

    //根据状态查询订单
    @Override
    public ResponseResult<List<AppointmentOrder>> getUserAppointmentsByStatus(HttpServletRequest httpRequest, Integer status) {
        User currentUser = userServiceUtils.getCurrentUser(httpRequest);
        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        List<AppointmentOrder> orders = this.lambdaQuery()
                .eq(AppointmentOrder::getUserId, currentUser.getId()) // 确保只查询当前用户的订单
                .eq(status != null, AppointmentOrder::getStatus, status)// 如果状态不为空，添加状态查询条件
                .list();

        enrichOrderDetails(orders);
        return ResponseResult.success(orders);
    }

    // 根据用户ID查询订单
    private void enrichOrderDetails(List<AppointmentOrder> orders) {
        if (orders == null || orders.isEmpty()) return;

        // 批量获取关联数据
        Map<Integer, Vehicle> vehicleMap = getVehicleMap(orders);
        Map<Integer, ServiceItem> serviceMap = getServiceMap(orders);
        List<Integer> userIds = orders.stream()
                .map(AppointmentOrder::getUserId)
                .distinct()// 去重
                .collect(Collectors.toList());// 收集到列表
        Map<Integer, User> userMap = userService.listByIds(userIds)
                .stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));// 收集到Map

        // 填充订单详情
        orders.forEach(order -> {
            Vehicle vehicle = vehicleMap.get(order.getVehicleId());
            if (vehicle != null) {
                order.setModel(vehicle.getModel());
            }

            ServiceItem service = serviceMap.get(order.getServiceId());
            if (service != null) {
                order.setServiceName(service.getServiceName());
            }
            if (vehicle != null) {
                order.setModel(vehicle.getModel());
                order.setLicensePlate(vehicle.getLicensePlate()); // 新增车牌号设置
            }
            User user = userMap.get(order.getUserId());
            if (user != null) {
                order.setUsername(user.getUsername());
            }
            order.setCommentStatus(order.getCommentStatus());
            order.setOrderNumber(order.getOrderNumber());
            order.setFormattedAppointmentTime(order.getFormattedAppointmentTime());
        });
    }

    // 提取车辆查询逻辑
    private Map<Integer, Vehicle> getVehicleMap(List<AppointmentOrder> orders) {
        List<Integer> vehicleIds = orders.stream()
                .map(AppointmentOrder::getVehicleId)
                .distinct()
                .collect(Collectors.toList());

        return vehicleService.listByIds(vehicleIds)
                .stream()
                .collect(Collectors.toMap(Vehicle::getId, Function.identity()));
    }

    // 提取服务项查询逻辑
    private Map<Integer, ServiceItem> getServiceMap(List<AppointmentOrder> orders) {
        List<Integer> serviceIds = orders.stream()
                .map(AppointmentOrder::getServiceId)
                .distinct()
                .collect(Collectors.toList());

        return serviceItemService.listByIds(serviceIds)
                .stream()
                .collect(Collectors.toMap(ServiceItem::getId, Function.identity()));
    }

    //更新订单状态
    @Override
    public ResponseResult<AppointmentOrder> updateAppointmentStatus(OrderUpdateRequest request, HttpServletRequest httpRequest) {
        if (userServiceUtils.IsAdmin(httpRequest) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (userServiceUtils.IsAdmin(httpRequest) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        AppointmentOrder order = this.getById(request.getId());
        if (order == null) {
            return ResponseResult.fail(404, "订单不存在", null);
        }

        // 更新订单状态
        if (request.getStatus() != null) {
            order.setStatus(request.getStatus());
        }
        // 更新技师id
        order.setStaffId(request.getStaffId());
        // 更新预计完成时间
        if (request.getEstimatedCompletion() != null) {
            order.setEstimatedCompletion(
                    Date.from(request.getEstimatedCompletion().atZone(ZoneId.systemDefault()).toInstant())
            );
        }

        this.updateById(order);
        return ResponseResult.success(order);
    }
    //删除订单
    @Override
    public ResponseResult<Boolean> deleteOrder(Integer orderId, HttpServletRequest request) {
        // 权限验证
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限删除订单", null);
        }

        // 检查订单是否存在
        AppointmentOrder order = this.getById(orderId);
        if (order == null) {
            return ResponseResult.fail(404, "订单不存在", null);
        }

        // 执行删除
        boolean result = this.removeById(orderId);
        return ResponseResult.success(200, "删除成功", result);
    }
    @Override
    public ResponseResult<Boolean> cancelOrderByUser(Integer orderId, HttpServletRequest request) {
        // 验证用户登录
        User currentUser = userServiceUtils.getCurrentUser(request);
        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 检查订单是否存在
        AppointmentOrder order = this.getById(orderId);
        if (order == null) {
            return ResponseResult.fail(404, "订单不存在", null);
        }

        // 验证订单是否属于当前用户
        if (!order.getUserId().equals(currentUser.getId())) {
            return ResponseResult.fail(403, "无权取消该订单", null);
        }

        // 执行删除
        boolean result = this.removeById(orderId);
        return ResponseResult.success(200, "取消成功", result);
    }
    @Override
    public ResponseResult<List<AppointmentOrder>> searchOrders(
            Integer id, String model, String serviceName,
            LocalDateTime startDate, LocalDateTime endDate,
            Integer status, HttpServletRequest request) {

        User currentUser = userServiceUtils.getCurrentUser(request);
        if (currentUser == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }

        // 构建查询条件
        LambdaQueryWrapper<AppointmentOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppointmentOrder::getUserId, currentUser.getId())
                .eq(id != null, AppointmentOrder::getId, id)
                .eq(status != null, AppointmentOrder::getStatus, status);

        // 执行查询
        List<AppointmentOrder> orders = this.list(queryWrapper);

        // 过滤其他条件
        orders = orders.stream()
                .filter(order -> {
                    boolean match = true;
                    if (model != null) {
                        Vehicle vehicle = vehicleService.getById(order.getVehicleId());
                        match = match && vehicle != null && vehicle.getModel().contains(model);
                    }
                    if (serviceName != null) {
                        ServiceItem service = serviceItemService.getById(order.getServiceId());
                        match = match && service != null && service.getServiceName().contains(serviceName);
                    }
                    if (startDate != null) {
                        Date start = Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant());
                        match = match && order.getAppointmentTime().after(start);
                    }
                    if (endDate != null) {
                        Date end = Date.from(endDate.atZone(ZoneId.systemDefault()).toInstant());
                        match = match && order.getAppointmentTime().before(end);
                    }
                    return match;
                })
                .collect(Collectors.toList());

        // 填充订单详情
        enrichOrderDetails(orders);
        return ResponseResult.success(orders);
    }
}




